/*************************************************************************
    > File Name: 1.udp_server.c
    > Author: Ykk
    > Mail: 3393579535@qq.com 
    > Created Time: 2023年05月30日 星期二 21时05分01秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

int main(int argc,char *argv[])
{
	//创建套接字
	int	fd = socket(AF_INET,SOCK_DGRAM,0);
	//绑定
	struct sockaddr_in myaddr;
	myaddr.sin_family = AF_INET;
	myaddr.sin_port = htons(8888);
	//inet_pton
	myaddr.sin_addr.s_addr = inet_addr("192.168.152.129");
	//inet_addr只能用于ipv4
	int ret = bind(fd,(struct sockaddr *)&myaddr,sizeof(myaddr));
	if(ret < 0)
	{
		perror("bind");
		return 1;
	}
	//读写
	char buf[1024];
	struct sockaddr_in cliaddr;
	socklen_t len = sizeof(cliaddr);
	while(1)
	{
		bzero(&buf,sizeof(buf));
		int n = recvfrom(fd,buf,sizeof(buf),0,(struct sockaddr *)&cliaddr,&len);
		if(n < 0)
		{
			perror("recvfrom");
			break;
		}
		else
		{
			printf("client==>%s\n",buf);
			sendto(fd,buf,n,0,(struct sockaddr *)&cliaddr,len);
			bzero(&buf,sizeof(buf));
		}
	}
	//关闭
	close(fd);

	return 0;	
}


